import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import moment from 'moment';
import requests from '../utils/requests';
import { message } from 'ant-design-vue';

export const useChatStore = defineStore('chat', () => {
  // 状态
  const messageList = ref([]);
  const selectedContact = ref(null);
  const chatMessages = ref([]);
  const isLoading = ref(false);
  
  // 获取聊天列表
  const fetchChatsList = async () => {
    try {
      isLoading.value = true;
      const res = await requests.post('/api/externalContacts/chatsList', {});
      if (res.data && res.data.result) {
        // 对返回的数据按时间戳进行降序排序，并格式化显示时间
        messageList.value = res.data.result
          .sort((a, b) => new Date(b.ts) - new Date(a.ts))
          .map(item => {
            const msgTime = moment(item.ts, "YYYY/MM/DD HH:mm:ss");
            const now = moment();
            const isToday = msgTime.isSame(now, 'day');
            
            return {
              ...item,
              _originalTs: item.ts, // 保存原始时间戳
              ts: isToday ? 
                msgTime.format("HH:mm") : // 当天消息只显示时分
                msgTime.format("MM月DD日 HH:mm") // 非当天消息显示月日时分
            };
          });
      }
      
      isLoading.value = false;
      return messageList.value;
    } catch (error) {
      isLoading.value = false;
      message.error('获取聊天列表失败');
      return [];
    }
  };
  
  // 获取聊天记录
  const fetchChatMessages = async (contact) => {
    if (!contact) return;
    
    try {
      isLoading.value = true;
      selectedContact.value = contact;
      
      const res = await requests.post('/api/externalRecordMessages/recordMessages', {
        contactId: contact.contactId,
        uid: contact.uid,
        page: '1',
        pageSize: '100',
      });
      
      if (res.data && res.data.result && Array.isArray(res.data.result.items)) {
        // 按时间戳升序排序，确保最新消息在底部显示
        chatMessages.value = res.data.result.items
          .sort((a, b) => new Date(a.ts) - new Date(b.ts))
          .map(msg => formatMessage(msg));
        
        // 清除未读消息计数
        messageList.value = messageList.value.map(m =>
          m.contactId === contact.contactId ? { ...m, count: '' } : m
        );
      } else {
        chatMessages.value = [{
          payload: { text: '暂无聊天记录' },
          time: new Date().toLocaleTimeString(),
          isMe: false,
          dr: 1,
          msgType: 0
        }];
      }
      
      isLoading.value = false;
      return chatMessages.value;
    } catch (error) {
      isLoading.value = false;
      message.error('获取聊天记录失败');
      chatMessages.value = [{
        payload: { text: '加载失败' },
        time: new Date().toLocaleTimeString(),
        isMe: false,
        dr: 1,
        msgType: 0
      }];
      return chatMessages.value;
    }
  };
  
  // 发送消息
  // 发送消息
  const sendMessage = async (text) => {
    if (!text.trim() || !selectedContact.value) return null;
    
    // 生成时间戳和消息唯一ID
    const timestamp = Date.now();
    const packedId = `${selectedContact.value.uid}_${selectedContact.value.contactId}_${timestamp}`;
    
    // 创建临时消息对象
    const tempMessage = {
      payload: { 
        text: text,
        type: 'text'
      },
      time: new Date().toLocaleTimeString(),
      isMe: true,
      dr: 0,
      msgType: 0,
      packedId: packedId,
      status: 'sending'
    };
    
    // 将临时消息添加到聊天记录中
    chatMessages.value.push(tempMessage);
    
    try {
      // 构建发送消息的请求参数
      const params = {
        contactId: selectedContact.value.contactId,
        text: text,
        force: false,
        packedId: packedId,
        uid: selectedContact.value.uid,
        payload: {
          type: 'text',
          from: selectedContact.value.uid,
          to: selectedContact.value.contactId,
          context: {
            text: text,
            trText: ''
          }
        }
      };
      
      // 发送消息到服务器
      const response = await requests.post('/api/externalCustomerSystem/sendTextAsync?force=false', params);
      
      // 更新消息状态
      const messageIndex = chatMessages.value.findIndex(msg => msg.packedId === packedId);
      if (messageIndex !== -1) {
        chatMessages.value[messageIndex].status = 'sent';
      }
      
      // 发送成功后，更新未读状态
      const contactIndex = messageList.value.findIndex(msg => msg.contactId === selectedContact.value.contactId);
      if (contactIndex !== -1) {
        messageList.value[contactIndex] = {
          ...messageList.value[contactIndex],
          isRead: true,
          unRead: 0
        };
      }
      
      return response;
    } catch (error) {
      // 更新消息状态为发送失败
      const messageIndex = chatMessages.value.findIndex(msg => msg.packedId === packedId);
      if (messageIndex !== -1) {
        chatMessages.value[messageIndex].status = 'failed';
      }
      
      message.error('发送消息失败');
      return null;
    }
  };
  
  // 接收新消息
  const receiveMessage = (messageData) => {
    try {
      
      // 创建新消息对象，正确处理数据结构
      const newMessage = {
        payload: {
          text: messageData.Payload?.Text || '空消息',
          trText: messageData.Payload?.TrText,
          media: messageData.Payload?.Media || [],
          contacts: messageData.Payload?.Contacts,
          contactsname: messageData.Payload?.Contactsname,
          linkBody: messageData.Payload?.LinkBody
        },
        time: moment(messageData.Ts).format('HH:mm'),
        isMe: messageData.Dr === 0,
        dr: messageData.Dr || 0,
        msgType: messageData.MsgType || 0,
        status: 'received',
        packedId: messageData.Packedid,
        msgId: messageData.MsgId
      };
      
      // 检查消息是否属于当前选中的联系人
      const isCurrentContact = selectedContact.value && 
        (messageData.From === selectedContact.value.contactId || 
         messageData.To === selectedContact.value.contactId);
         
      if (isCurrentContact) {
        // 使用响应式数组方法添加消息
        chatMessages.value = [...chatMessages.value, newMessage];
      }
      
      // 更新消息列表
      const listItemIndex = messageList.value.findIndex(item => 
        item.contactId === (messageData.Dr === 1 ? messageData.From : messageData.To)
      );
      
      if (listItemIndex !== -1) {
        // 创建新的消息列表项
        const updatedMessageList = [...messageList.value];
        updatedMessageList[listItemIndex] = {
          ...messageList.value[listItemIndex],
          payload: {
            text: newMessage.payload.text
          },
          ts: moment(messageData.Ts).format("MMM Do YY"),
          count: !isCurrentContact ? 
            (parseInt(messageList.value[listItemIndex].count) || 0) + 1 : 
            messageList.value[listItemIndex].count
        };
        
        // 更新消息列表
        messageList.value = updatedMessageList;
      }
    } catch (error) {
      console.error('处理新消息时出错:', error, error.stack);
    }
  };
  
  // 格式化消息对象
  const formatMessage = (msg) => {
    let messageContent = { text: '消息内容为空' };
    
    try {
      if (msg.payload) {
        messageContent = { ...msg.payload };
        
        // 统一处理媒体文件链接
        if (msg.msgType !== 0 && messageContent.media) {
          // 修改这里：如果是数组，取第一个元素
          messageContent.media = Array.isArray(messageContent.media) 
            ? messageContent.media[0]?.replace('-internal', '') 
            : messageContent.media?.replace('-internal', '');
        }
        
        // 根据消息类型设置显示文本
        switch (msg.msgType) {
          case 0: // 文本消息
            messageContent.text = messageContent.text || '空文本消息';
            break;
          case 1: // 图片消息
            messageContent.text = '[图片消息]';
            break;
          case 2: // 语音消息
            messageContent.text = '[语音消息]';
            break;
          case 3: // 视频消息
            messageContent.text = '[视频消息]';
            break;
          case 4: // 链接消息
            messageContent.text = '[链接消息]';
            break;
          case 5: // 名片消息
            messageContent.text = '[名片消息]';
            break;
          case 21: // 商户超链
            messageContent.text = '[商户超链]';
            break;
          case 22: // 图文超链
            messageContent.text = '[图文超链]';
            break;
          case 11: // 语音通话
            messageContent.text = '[语音通话]';
            break;
          case 12: // 视频通话
            messageContent.text = '[视频通话]';
            break;
          default:
            messageContent.text = '未知消息类型';
        }
      }
    } catch (error) {
      messageContent = { text: '消息解析失败' };
    }
    
    return {
      payload: messageContent,
      time: new Date(msg.ts).toLocaleTimeString(),
      isMe: msg.dr === 0,
      dr: msg.dr,
      msgType: msg.msgType
    };
  };
  
  // 滚动到最新消息
  const scrollToBottom = () => {
    setTimeout(() => {
      const chatContainer = document.querySelector('.chat-messages');
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }
    }, 100);
  };
  
  // 在状态部分添加分组列表
  const groupList = ref([]);
  
  // 获取分组列表
  const fetchGroupList = async () => {
    try {
      const res = await requests.post('/api/externalContacts/groupList', {});
      if (res.data && res.data.result) {
        groupList.value = res.data.result;
        console.log('分组列表数据:', res.data.result);
      }
      return groupList.value;
    } catch (error) {
      console.error('获取分组列表失败:', error);
      message.error('获取分组列表失败');
      return [];
    }
  };
  
  // 在状态部分添加联系人详情列表
  const contactsList = ref([]);
  const groupDetailsList = ref([]);
  
  // 获取联系人详情列表
  const fetchContactsList = async () => {
    try {
      const res = await requests.post('/api/externalContacts/contacts', {});
      if (res.data && res.data.result) {
        contactsList.value = res.data.result;
        console.log('联系人详情数据:', res.data.result);
        
        // 筛选出groupId不等于"0"的数据
        const validGroups = res.data.result.filter(contact => contact.groupId !== "0");
        
        // 获取所有不重复的groupId
        const uniqueGroupIds = [...new Set(validGroups.map(contact => contact.groupId))];
        
        // 对每个groupId调用groupDetails接口
        for (const groupId of uniqueGroupIds) {
          fetchGroupDetails(groupId);
        }
      }
      return contactsList.value;
    } catch (error) {
      console.error('获取联系人详情失败:', error);
      message.error('获取联系人详情失败');
      return [];
    }
  };
  
  // 获取分组详情
  const fetchGroupDetails = async (groupId) => {
    try {
      const res = await requests.get(`/api/externalContacts/groupDetails/${groupId}`);
      if (res.data && res.data.result) {
        // 将获取到的分组详情添加到列表中
        groupDetailsList.value.push(res.data.result);
        console.log(`分组ID ${groupId} 详情:`, res.data.result);
      }
      return res.data?.result;
    } catch (error) {
      console.error(`获取分组ID ${groupId} 详情失败:`, error);
      message.error(`获取分组详情失败`);
      return null;
    }
  };

  // 在return中添加新的状态和方法
  return {
    messageList,
    selectedContact,
    chatMessages,
    isLoading,
    groupList,
    contactsList,
    groupDetailsList,     // 新增
    fetchContactsList,
    fetchGroupDetails,    // 新增
    fetchGroupList,
    fetchChatsList,
    fetchChatMessages,
    sendMessage,
    receiveMessage,
    scrollToBottom
  };
});